//
//  MemberView.swift
//  AirlineReservation
//
//  Created by Kevin on 2020/2/19.
//  Copyright © 2020 Kevin. All rights reserved.
//

import UIKit

class MemberView: UIView {
    
    // scrollview
    private var scrollView = UIScrollView()
    
    // 回调
    public var complete:((_ item:Int) -> Void)?
    
    public var memberZones:[MemberZoneInfo]? {
        didSet {
            updateLayout()
        }
    }
    
    override func layoutSubviews() {
        guard let zones = memberZones else {
            return
        }
        // 记录高度
        var tempHeight:CGFloat = 0
        // 摆放
        for i in 0..<zones.count {
            let member = SubMemberView()
            member.tag = i
            member.subMember = zones[i]
            member.frame = CGRect(x: 0, y: tempHeight, width: frame.width, height: 230)
            scrollView.addSubview(member)
            // 添加点击事件
            member.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(clickItem(tap:))))
            // 最后一个view高度
            tempHeight = member.frame.maxY + MARGIN25
        }
        // 设置scrollview
        addSubview(scrollView)
        scrollView.showsVerticalScrollIndicator = false
        scrollView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
        scrollView.contentSize = CGSize(width: SCREEN_WIDTH, height: tempHeight + MARGIN30)
    }
    
    @objc func clickItem(tap:UITapGestureRecognizer) -> Void {
        if let callback = complete ,let index = tap.view?.tag {
            callback(index)
        }
    }
    
    class SubMemberView: UIView {
        
        public var subMember:MemberZoneInfo?
        
        override func layoutSubviews() {
            guard let member = subMember else {
                return
            }
            // 宽度
            let w = frame.width - MARGIN * 2
            // 图片
            let imgView = UIButton()
            imgView.layer.cornerRadius = 8
            imgView.layer.masksToBounds = true
            imgView.isUserInteractionEnabled = false
            imgView.setImage(UIImage(named: member.picture!), for: .normal)
            imgView.frame = CGRect(x: MARGIN, y: MARGIN, width: w, height: 180)
            addSubview(imgView)
            // 描述
            let descView = UILabel(title: "", color: UIColor.black, size: 14)
            descView.text = member.activitydes!
            descView.isUserInteractionEnabled = false
            descView.frame = CGRect(x: MARGIN, y: imgView.frame.maxY + MARGIN, width: w, height: MARGIN)
            addSubview(descView)
            // 活动有效期
            let timeView = UILabel(title: "", color: UIColor.gray, size: 12)
            timeView.isUserInteractionEnabled = false
            timeView.text = "活动有效期：\(member.startdate!) 至 \(member.stopdate!)"
            timeView.frame = CGRect(x: MARGIN, y: descView.frame.maxY + MARGIN8, width: w, height: MARGIN)
            addSubview(timeView)
        }
    }
}
